package de.medieninf.android.sensimg;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

public class BallView extends View implements AccelerationListener {
	final static String TAG = "BallView";
	
	// the values as of the acceleration sensor
	private float xpos; // -10 .. 10
	private float ypos; 
	private float zpos;
	private int width;
	private int height;
	private int mindim;
	private Paint paint;
	private volatile KeyboardState keyboardState;

	public BallView(Context context) {
		super(context);
		init();
	}
	
	public BallView(Context context,  AttributeSet attributeSet) {
		super(context, attributeSet);
		init();
	}

	public BallView(Context context,  AttributeSet attributeSet, int defStyle) {
		super(context, attributeSet, defStyle);
		init();
	}
	
	private void init() {
		paint = new Paint();
		paint.setColor(Color.RED);
		setFocusable(true); // important for key events
		setFocusableInTouchMode(true);
		requestFocus(); // make sure we have focus
		Log.v(TAG, "initialized with init");
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		width = MeasureSpec.getSize(widthMeasureSpec);
		height = MeasureSpec.getSize(heightMeasureSpec);
		mindim = width < height ? width : height;
		// Log.v(TAG, "in onMeasure " + width + "x" + height);
	}
	
	public void update(float x, float y, float z) {
		xpos = x;
		ypos = y;
		zpos = z;
		invalidate();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        if (zpos < 0) {
            paint.setColor(Color.RED);        	
        } else {
        	paint.setColor(Color.BLUE);
        }
        zpos = zpos < 0 ? -zpos : zpos;
        int radius = (int) (((10.0-zpos)*mindim/20.0));
        if (radius < 4) 
        	radius = 4;
        int cx = width - ((int) ((xpos+10.0)*width/20.0));
        int cy = (int) ((ypos+10.0)*height/20.0);

        // Log.v(TAG, "onDraw " + xpos + " " + cx + " " + halfWidth);
        canvas.drawCircle(cx, cy, radius, paint);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyboardState != null)
			keyboardState.onKeyDown(keyCode, event);
		// Log.v(TAG, "String :" + keyboardState.getKeys());
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyboardState != null)
			keyboardState.onKeyUp(keyCode, event);
		// Log.v(TAG, "String :" + keyboardState.getKeys());
		return super.onKeyUp(keyCode, event);
	}
	
	public void setKeyboardState(KeyboardState keyboardState) {
		this.keyboardState = keyboardState;
	}
}
